<template>
    <button
        class="avatar-button"
        open-type="chooseAvatar"
        @chooseavatar="handleChooseAvatar"
        hover-class="none"
    >
        <slot></slot>
    </button>
</template>

<script setup>
/**
 * @description: 全局填充头像按钮组件，微信、支付宝小程序支持，请注意使用场景
 * @author yinzhi
 * @date 2025-03-12
 */
import { logger } from '@/utils/log.js'
import { getBaseUrl } from '@/libs/common/baseUrl.js'
import { useStore } from 'vuex'
const store = useStore()
import { computed } from 'vue'

const emit = defineEmits()

const token = computed(() => store.state.auth.token || '')

const upApi = computed(() => getBaseUrl() + '/admin/cms/oss/upload')
/**
 * 填充头像功能
 * @param e 回调返回的参数
 */
const handleChooseAvatar = e => {
    const tempAvatarUrl = e.detail?.avatarUrl || ''
    uni.hideLoading()
    uni.showLoading({
        title: '图片上传中...'
    })
    uni.uploadFile({
        // 上传路径
        url: upApi.value,
        filePath: tempAvatarUrl,
        name: 'file',
        fileType: 'image',
        header: {
            Authorization: token.value
        },
        formData: {},
        complete: res => {
            uni.hideLoading()
            const data = JSON.parse(res.data)
            if (res.statusCode === 200) {
                // 上传成功后抛出事件和接口数据，由父组件处理后续逻辑
                emit('init', data)
                return
            }
            logger.error({ '[handleChooseAvatar]-头像填充上传失败：': data })
            uni.showToast({
                title: '图片上传失败,请稍后再试',
                icon: 'none'
            })
        }
    })
}
</script>

<style lang="scss" scoped>
.avatar-button {
    display: block;
    margin: 0;
    padding-left: 0;
    padding-right: 0;
    line-height: 1;
    margin-right: 0;
    margin-left: 0;
    border-radius: 0;
    overflow: initial;
    background-color: transparent;
}

button::after {
    display: none;
}
</style>
